Page({
  data: {
    theme: 'light',
    showCallbackInfo: false,
    callbackType: '', // success, fail
    callbackMessage: '',
    docurl:'',
    title: '页面导航',
    apiName: ''
  },

  // API处理函数
  handleApiCall: function(e) {
    const apiName = e.currentTarget.dataset.apiname;
    
    this.setData({
      apiName: apiName
    });
    
    switch(apiName) {
      case 'EventChannel.emit':
        this.eventChannelEmitFunc();
        break;
      case 'EventChannel.off':
        this.eventChannelOffFunc();
        break;
      case 'EventChannel.on':
        this.eventChannelOnFunc();
        break;
      case 'EventChannel.once':
        this.eventChannelOnceFunc();
        break;
      case 'EventChannel.close':
        this.eventChannelCloseFunc();
        break;
      case 'EventChannel.test':
        this.testEventChannelFullFunc();
        break;
      default:
        this.showApiResult(`未知的API: ${apiName}`);
    }
  },

  // 表单数据变化回调
  getFormData(e) {
    const { formData } = e.detail;
    this.setData({
      formData: formData,
      showCallbackInfo: true,
      callbackMessage: '表单数据已更新',
      callbackType: 'success'
    });
  },
  
  // 显示API调用结果
  showApiResult(result) {
    // 判断结果是成功还是失败
    const isSuccess = !result || !result.error && (result.success !== false);
    
    this.setData({
      result: result,
      showCallbackInfo: true,
      callbackMessage: isSuccess ? 'API调用成功' : 'API调用失败',
      callbackType: isSuccess ? 'success' : 'fail'
    });
  },
  onLoad(object){
    this.setData({
      docurl:object.webUrl || ''
    })
  },
  onShareAppMessage() {
    return {
      title: '页面跳转',
      path: 'packageAPI/pages/page/navigator/navigator'
    }
  },

  // 显示回调信息
  showCallbackInfo(type, message) {
    this.setData({
      showCallbackInfo: true,
      callbackType: type,
      callbackMessage: message
    });
  },

  // 定义一个函数来处理跳转逻辑 
  navigateWithCallbacks(method, options, delay = 0, showResult = false) {
    const methodName = method.charAt(0).toUpperCase() + method.slice(1);

    // 处理URL参数，为需要传递参数的导航方法添加详细的成功信息
    if (options.url && ['navigateTo', 'redirectTo', 'reLaunch'].includes(method)) {
      // 在URL中添加详细信息参数占位符
      if (!options.url.includes('detailInfo=')) {
        const separator = options.url.includes('?') ? '&' : '?';
        options.url = `${options.url}${separator}detailInfo=placeholder`;
      }
    }

    // 立即执行跳转操作
    wx[method]({
      ...options,
      success: (res) => {
        const successMessage = `${methodName}执行成功 ${JSON.stringify(res)}`;
        this.showCallbackInfo('success',successMessage)
        
        // 如果需要显示结果，调用showApiResult方法
        if (showResult) {
          this.showApiResult(res);
        }
      },
      fail: (error) => {
        const errorMessage = `${methodName}跳转失败`;
        const detailedError = {
          errMsg: error.errMsg || '未知错误',
          ...error
        };
      this.showCallbackInfo('fail', `${errorMessage}: ${JSON.stringify(detailedError)}`);
      
        // 失败时也可以显示错误结果
        if (showResult) {
          this.showApiResult(error);
        }
      },
    });
  },

  navigateTo() {
    this.navigateWithCallbacks('navigateTo', {
      url: './targetPage?from=navigateTo&status=success&message=navigateTo跳转成功&weburl='+this.data.docurl,
      events: {
        // 监听来自目标页面的事件
        onMessageFromTargetPage: (data) => {
          this.showCallbackInfo('success', `收到目标页面消息: ${JSON.stringify(data)}`);
        }
      },
      success: (res) => {
        // 获取eventChannel对象
        const eventChannel = res.eventChannel;
        // 向目标页面发送消息
        eventChannel.emit('onMessageFromNavigator', {
          data: '来自导航页面的初始消息',
          timestamp: new Date().getTime()
        });
      }
    }, 0, true); // 第四个参数设为true表示需要显示结果
  },

  // 自定义路由示例
  // 在开发者工具中预览效果
  navigateToWithCustomRoute() {
    try {
      // 使用自定义路由
      wx.navigateTo({
        url: './targetPage?from=customRoute&status=success&message=自定义路由跳转成功&weburl='+this.data.docurl,
        routeType: 'slide',
        success: (res) => {
          const successMessage = '已使用自定义路由类型"slide"进行跳转';
          this.showCallbackInfo('success', successMessage);
          // 显示结果
          this.showApiResult(res);
        },
        fail: (error) => {
          const errorMessage = `自定义路由跳转失败: ${error.message}`;
          this.showCallbackInfo('fail', errorMessage);
          // 显示错误结果
          this.showApiResult(error);
        }
      });
    } catch (error) {
      const errorMessage = `自定义路由跳转失败: ${error.message}`;
      this.showCallbackInfo('fail', errorMessage);
      // 显示异常结果
      this.showApiResult({ error: error.message });
    }
  },

  navigateBack() {
    this.navigateWithCallbacks('navigateBack', {
      delta: 1
    }, 0, true); // 第四个参数设为true表示需要显示结果
  },

  redirectTo() {
    this.navigateWithCallbacks('redirectTo', {
      url: './targetPage?from=redirectTo&status=success&message=redirectTo跳转成功'
    }, 0, true); // 第四个参数设为true表示需要显示结果
  },

  switchTab() {
    this.navigateWithCallbacks('switchTab', {
      url: '/page/component/index?from=switchTab&status=success&message=switchTab跳转成功'
    }, 0, true); // 第四个参数设为true表示需要显示结果
  },

  reLaunch() {
    this.navigateWithCallbacks('reLaunch', {
      url: './targetPage?from=reLaunch&status=success&message=reLaunch跳转成功'
    }, 0, true); // 第四个参数设为true表示需要显示结果
  },

  testNavigateFail() {
    this.navigateWithCallbacks('navigateTo', {
      url: './nonExistentPage' 
    }, 0, true); // 第四个参数设为true表示需要显示结果
  },

  eventChannelEmit() {
    try {
      if (this.getOpenerEventChannel) {
        const eventChannel = this.getOpenerEventChannel();
        const message = {
          data: '来自当前页面的消息',
          timestamp: new Date().getTime()
        };
        eventChannel.emit('customEvent', message);
        this.showCallbackInfo('success', `EventChannel.emit: 发送消息 ${JSON.stringify(message)}`);
        // 显示结果
        this.showApiResult({ success: true, message });
      } else {
        const errorMessage = '当前页面没有可用的EventChannel';
        this.showCallbackInfo('fail', errorMessage);
        // 显示错误结果
        this.showApiResult({ success: false, error: errorMessage });
      }
    } catch (error) {
      const errorMessage = `EventChannel.emit执行异常: ${error.message}`;
      this.showCallbackInfo('fail', errorMessage);
      // 显示异常结果
      this.showApiResult({ success: false, error: error.message });
    }
  },

  eventChannelOff() {
    try {
      if (this.getOpenerEventChannel) {
        const eventChannel = this.getOpenerEventChannel();
        // 移除事件监听
        const eventName = 'customEvent';
        
        // 检查是否有保存的事件处理函数引用
        if (this._eventHandlers && this._eventHandlers[eventName]) {
          eventChannel.off(eventName, this._eventHandlers[eventName]);
          // 移除保存的引用
          delete this._eventHandlers[eventName];
          const successMessage = `EventChannel.off: 成功移除事件监听 '${eventName}'`;
          this.showCallbackInfo('success', successMessage);
          // 显示结果
          this.showApiResult({ success: true, eventName, message: successMessage });
        } else {
          const errorMessage = `EventChannel.off: 没有找到事件 '${eventName}' 的处理函数引用`;
          this.showCallbackInfo('fail', errorMessage);
          // 显示错误结果
          this.showApiResult({ success: false, eventName, error: errorMessage });
        }
      } else {
        const errorMessage = '当前页面没有可用的EventChannel';
        this.showCallbackInfo('fail', errorMessage);
        // 显示错误结果
        this.showApiResult({ success: false, error: errorMessage });
      }
    } catch (error) {
      const errorMessage = `EventChannel.off执行异常: ${error.message}`;
      this.showCallbackInfo('fail', errorMessage);
      // 显示异常结果
      this.showApiResult({ success: false, error: error.message });
    }
  },

  eventChannelOn() {
    try {
      if (this.getOpenerEventChannel) {
        const eventChannel = this.getOpenerEventChannel();
        const eventName = 'customEvent';
        const eventHandler = (data) => {
          const message = `EventChannel.on: 收到消息 ${JSON.stringify(data)}`;
          this.showCallbackInfo('success', message);
          // 显示接收到的消息
          this.showApiResult({ success: true, eventName, data });
        };
        eventChannel.on(eventName, eventHandler);
        const successMessage = `EventChannel.on: 开始监听事件 '${eventName}'`;
        this.showCallbackInfo('success', successMessage);
        // 显示设置监听结果
        this.showApiResult({ success: true, eventName, message: successMessage });
        // 保存事件处理函数引用，以便后续可以移除监听
        this._eventHandlers = this._eventHandlers || {};
        this._eventHandlers[eventName] = eventHandler;
      } else {
        const errorMessage = '当前页面没有可用的EventChannel';
        this.showCallbackInfo('fail', errorMessage);
        // 显示错误结果
        this.showApiResult({ success: false, error: errorMessage });
      }
    } catch (error) {
      const errorMessage = `EventChannel.on执行异常: ${error.message}`;
      this.showCallbackInfo('fail', errorMessage);
      // 显示异常结果
      this.showApiResult({ success: false, error: error.message });
    }
  },

  eventChannelOnce() {
    try {
      if (this.getOpenerEventChannel) {
        const eventChannel = this.getOpenerEventChannel();
        const eventName = 'customEventOnce';
        eventChannel.once(eventName, (data) => {
          const message = `EventChannel.once: 收到消息 ${JSON.stringify(data)}`;
          this.showCallbackInfo('success', message);
          // 显示接收到的消息
          this.showApiResult({ success: true, eventName, data });
        });
        const successMessage = `EventChannel.once: 开始监听一次性事件 '${eventName}'`;
        this.showCallbackInfo('success', successMessage);
        // 显示设置监听结果
        this.showApiResult({ success: true, eventName, message: successMessage });
      } else {
        const errorMessage = '当前页面没有可用的EventChannel';
        this.showCallbackInfo('fail', errorMessage);
        // 显示错误结果
        this.showApiResult({ success: false, error: errorMessage });
      }
    } catch (error) {
      const errorMessage = `EventChannel.once执行异常: ${error.message}`;
      this.showCallbackInfo('fail', errorMessage);
      // 显示异常结果
      this.showApiResult({ success: false, error: error.message });
    }
  },
  
  eventChannelClose() {
    try {
      if (this.getOpenerEventChannel) {
        if (this._eventHandlers) {
          const eventChannel = this.getOpenerEventChannel();
          for (const eventName in this._eventHandlers) {
            if (this._eventHandlers.hasOwnProperty(eventName)) {
              eventChannel.off(eventName, this._eventHandlers[eventName]);
            }
          }
          this._eventHandlers = {};
        }
        
        const successMessage = 'EventChannel: 已清理所有事件监听';
        this.showCallbackInfo('success', successMessage);
        // 显示结果
        this.showApiResult({ success: true, message: successMessage });
      } else {
        const errorMessage = '当前页面没有可用的EventChannel';
        this.showCallbackInfo('fail', errorMessage);
        // 显示错误结果
        this.showApiResult({ success: false, error: errorMessage });
      }
    } catch (error) {
      const errorMessage = `EventChannel.close执行异常: ${error.message}`;
      this.showCallbackInfo('fail', errorMessage);
      // 显示异常结果
      this.showApiResult({ success: false, error: error.message });
    }
  },
  routerAddRouteBuilder() {
    try {
      this.showCallbackInfo('success', '正在添加自定义路由动画...');
      
      const slideRouteBuilder = (customRouteContext) => {
        const { primaryAnimation } = customRouteContext
        console.log('primaryAnimation:', primaryAnimation)
        // 使用兼容方式定义动画处理函数
        const handlePrimaryAnimation = function() {
          'worklet' 
          try {
            const { windowHeight } = wx.getSystemInfoSync()
            const transY = windowHeight * (1 - primaryAnimation.value)
            return {
              transform: `translateY(${transY}px)`,
            }
          } catch (e) {
            console.error('动画计算出错:', e)
            return {} 
          }
        }
        
        return {
          handlePrimaryAnimation
        }
      }
      console.log('slideRouteBuilder:', typeof wx !== 'undefined' && wx.router && typeof wx.router.addRouteBuilder === 'function')
      if (typeof wx !== 'undefined' && wx.router && typeof wx.router.addRouteBuilder === 'function') {          
        try {
          wx.router.addRouteBuilder('slide', slideRouteBuilder)
          const successMessage = '已成功添加自定义路由动画(从上向上出现)\n请点击"使用自定义路由(slide)"按钮体验页面跳转效果';
          this.showCallbackInfo('success', successMessage);
          // 显示结果
          this.showApiResult({ success: true, method: 'routerAddRouteBuilder', routeType: 'slide', message: successMessage });
        } catch (addError) {
          console.error('添加路由构建器失败:', addError)
          const errorMessage = `添加路由构建器失败: ${addError.message || '未知错误'}`;
          this.showCallbackInfo('fail', errorMessage);
          // 显示错误结果
          this.showApiResult({ success: false, method: 'routerAddRouteBuilder', error: addError.message || '未知错误' });
        }
      } else {
        console.log('wx.router.addRouteBuilder 不支持')
        const errorMessage = '当前环境不支持wx.router.addRouteBuilder';
        this.showCallbackInfo('fail', errorMessage);
        // 显示错误结果
        this.showApiResult({ success: false, method: 'routerAddRouteBuilder', error: errorMessage });
      }
    } catch (error) {
      console.error('routerAddRouteBuilder执行异常:', error)
      const errorMessage = `执行异常: ${error.message || '未知错误'}`;
      this.showCallbackInfo('fail', errorMessage);
      // 显示异常结果
      this.showApiResult({ success: false, method: 'routerAddRouteBuilder', error: error.message || '未知错误' });
    }
  },   
  routerGetRouteContext() {
    try {
      if (wx.router && wx.router.getRouteContext) {
        const routeContext = wx.router.getRouteContext(this);
        const successMessage = `已获取路由上下文对象: ${JSON.stringify(routeContext)}`;
        this.showCallbackInfo('success', successMessage);
        // 显示结果
        this.showApiResult({ success: true, method: 'routerGetRouteContext', routeContext });
      } else {
        const errorMessage = 'wx.router.getRouteContext 不支持';
        this.showCallbackInfo('fail', errorMessage);
        // 显示错误结果
        this.showApiResult({ success: false, method: 'routerGetRouteContext', error: errorMessage });
      }
    } catch (error) {
      const errorMessage = `wx.router.getRouteContext执行异常: ${error.message}`;
      this.showCallbackInfo('fail', errorMessage);
      // 显示异常结果
      this.showApiResult({ success: false, method: 'routerGetRouteContext', error: error.message });
    }
  },

  routerRemoveRouteBuilder() {
    try {
      if (wx.router && wx.router.removeRouteBuilder) {
        wx.router.removeRouteBuilder('slide');
        const successMessage = '已移除自定义路由类型"slide"';
        this.showCallbackInfo('success', successMessage);
        // 显示结果
        this.showApiResult({ success: true, method: 'routerRemoveRouteBuilder', routeType: 'slide', message: successMessage });
      } else {
        const errorMessage = 'wx.router.removeRouteBuilder 不支持';
        this.showCallbackInfo('fail', errorMessage);
        // 显示错误结果
        this.showApiResult({ success: false, method: 'routerRemoveRouteBuilder', error: errorMessage });
      }
    } catch (error) {
      const errorMessage = `wx.router.removeRouteBuilder执行异常: ${error.message}`;
      this.showCallbackInfo('fail', errorMessage);
      // 显示异常结果
      this.showApiResult({ success: false, method: 'routerRemoveRouteBuilder', error: error.message });
    }
  },
  rewriteRoute() {
    try {
      if (wx.rewriteRoute) {
        wx.rewriteRoute({
          url: './targetPage?from=rewriteRoute&status=success&message=rewriteRoute重写成功',
          preserveQuery: false,
          success: (res) => {
            const successMessage = '已尝试重写路由事件';
            this.showCallbackInfo('success', successMessage);
            // 显示结果
            this.showApiResult({ success: true, method: 'rewriteRoute', message: successMessage, result: res });
          },
          fail: (error) => {
            const errorMessage = `wx.rewriteRoute调用失败: ${error.message}`;
            this.showCallbackInfo('fail', errorMessage);
            // 显示错误结果
            this.showApiResult({ success: false, method: 'rewriteRoute', error: error.message });
          }
        });
      } else {
        const errorMessage = 'wx.rewriteRoute 不支持';
        this.showCallbackInfo('fail', errorMessage);
        // 显示错误结果
        this.showApiResult({ success: false, method: 'rewriteRoute', error: errorMessage });
      }
    } catch (error) {
      const errorMessage = `wx.rewriteRoute执行异常: ${error.message}`;
      this.showCallbackInfo('fail', errorMessage);
      // 显示异常结果
      this.showApiResult({ success: false, method: 'rewriteRoute', error: error.message });
    }
  },

  onLoad() {
    // 获取屏幕宽度，用于自定义路由动画
    const { windowWidth } = wx.getSystemInfoSync()
    this.windowWidth = windowWidth
    
    this.setData({
      theme: wx.getSystemInfoSync().theme || 'light'
    })

    if (wx.onThemeChange) {
      wx.onThemeChange(({ theme }) => {
        this.setData({ theme })
      })
    }
    
    // 初始化事件处理器存储对象
    this._eventHandlers = this._eventHandlers || {};
  },
  
  // 测试EventChannel全套功能的方法
  testEventChannelFull() {
    try {
      // 1. 首先设置on监听
      this.eventChannelOn();
      
      // 2. 延迟发送消息以测试监听效果
      setTimeout(() => {
        if (this.getOpenerEventChannel) {
          const eventChannel = this.getOpenerEventChannel();
          const message = {
            data: 'EventChannel全套测试消息',
            timestamp: new Date().getTime(),
            testType: 'full'
          };
          eventChannel.emit('customEvent', message);
        }
      }, 1000);
      
      // 3. 再设置once监听
      setTimeout(() => {
        try {
          if (this.getOpenerEventChannel) {
            const eventChannel = this.getOpenerEventChannel();
            const eventName = 'customEventOnce';
            eventChannel.once(eventName, (data) => {
              const message = `EventChannel.once: 收到测试消息 ${JSON.stringify(data)}`;
              this.showCallbackInfo('success', message);
              // 显示接收到的消息
              this.showApiResult({ success: true, eventName, data });
            });
            
            // 发送一次性事件消息
            setTimeout(() => {
              eventChannel.emit(eventName, {
                data: '一次性事件测试消息',
                timestamp: new Date().getTime(),
                testType: 'once'
              });
            }, 500);
            
            // 再次发送一次性事件消息，验证只触发一次
            setTimeout(() => {
              eventChannel.emit(eventName, {
                data: '这条消息不会被接收',
                timestamp: new Date().getTime(),
                testType: 'once-ignored'
              });
              this.showCallbackInfo('success', '验证完成：EventChannel.once 只触发了一次');
            }, 1500);
          }
        } catch (error) {
          const errorMessage = `EventChannel测试失败: ${error.message}`;
          this.showCallbackInfo('fail', errorMessage);
        }
      }, 2000);
      
      // 4. 最后移除监听
      setTimeout(() => {
        this.eventChannelOff();
        this.showCallbackInfo('success', 'EventChannel全套测试完成');
      }, 4000);
      
    } catch (error) {
      const errorMessage = `EventChannel测试执行异常: ${error.message}`;
      this.showCallbackInfo('fail', errorMessage);
    }
  },

  // API处理函数实现
  eventChannelEmitFunc: function() {
    this.eventChannelEmit();
  },

  eventChannelOffFunc: function() {
    this.eventChannelOff();
  },

  eventChannelOnFunc: function() {
    this.eventChannelOn();
  },

  eventChannelOnceFunc: function() {
    this.eventChannelOnce();
  },

  eventChannelCloseFunc: function() {
    this.eventChannelClose();
  },

  testEventChannelFullFunc: function() {
    this.testEventChannelFull();
  }
})
